<?php
// This file is part of CorfoWS for Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * @package   local_corfows
 * @author    Hackware Human <human@hackware.cl>
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

namespace local_corfows;

defined('MOODLE_INTERNAL') || die();

class http_request {
    public function __construct() {
        $this->env = getenv('CORFOWS_ENV') ?
            getenv('CORFOWS_ENV') : 'production';
    }

    protected static function log($data) {
        global $CFG;
        file_put_contents(
            $CFG->dataroot . '/corfows.log',
            date('c') . " $data\n",
            FILE_APPEND
        );
    }

    public function post() {
        $ch = curl_init($this->url);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $this->data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if(getenv('CORFOWS_DONT_VERIFY_SSL')) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        }

        $response = curl_exec($ch);
        if(getenv('CORFOWS_LOG')) {
            if (curl_error($ch)) $response = curl_error($ch);
            static::log(
                $this->url . ' - ' .
                json_encode( $this->data )  . ' - ' .
                $response
            );
        }
        curl_close($ch);

        return $response;
    }

    protected static function bearer_token() {
        $request = new static();

        if ($request->env === 'testing') {
            $request->url = 'https://apitest.corfo.cl:9101/api/oauth/token';
        } else if ($request->env === 'production') {
            $request->url = 'https://www.corfo.cl/oauth/token';
        }

        $request->data = http_build_query([
            'scope' => 'resource.READ',
            'client_secret' => getenv('CORFOWS_CLIENT_SECRET'),
            'client_id' => getenv('CORFOWS_CLIENT_ID'),
            'grant_type' => 'client_credentials'
        ], '', '&');

        $request->headers = [
            'Content-type: application/x-www-form-urlencoded;charset=utf-8'
        ];

        $response = $request->post();
        return $response ? json_decode($response) : false;
    }

    public static function validation($codcert) {
        \require_login();

        $tokenresp = static::bearer_token();

        if (property_exists($tokenresp, 'error_description')) {
            return $tokenresp;
        }

        global $USER, $COURSE;

        $request = new static();

        if ($request->env === 'testing') {
            $request->url = 'https://apitest.corfo.cl:9101/OAG/API_WS_MOOC/Validate';
        } else if ($request->env === 'production') {
            $request->url = 'https://www.corfo.cl/api/StartupJourneyWSApiMooc/Validate';
        }

        $request->data = json_encode([
            'Institucion' => getenv('CORFOWS_INSTITUTION_ID'),
            'Rut' => $USER->username,
            'Contenido' => $COURSE->idnumber,
            'NombreContenido' => $COURSE->fullname,
            'CodigoCertificacion' => $codcert,
            'Evaluacion' => null,
            'Correo' => $USER->email
        ]);

        $request->headers = [
            "Authorization:Bearer $tokenresp->access_token",
            'Content-Type:application/json',
        ];

        $response = $request->post();
        return $response ? json_decode($response) : false;
    }
}
